package cn.tedu.oopTestConstructor.cn.tedu;


import java.util.Objects;

/**
 * @author SWJ
 * @create 2021-06-15 14:24
 * 本类用于测试顶级父类Object
 */
public class TestObject {
    public static void main(String[] args) {
        /**创建对象并对象属性赋值*/
        Student s = new Student(20, "yaya");
        Student s2 = new Student(20, "yaya");
        System.out.println(s);
        /**cn.tedu.oopTestConstructor.cn.tedu.Student@4554617c
         * 地址值
         * 添加tostring方法后打印出
         * 重写Object中的toString()
         *      * 打印Student{year=20, name='yaya'}
         *      * 打印的对象的属性与属性值*/
        System.out.println(s.hashCode());
        //哈希码值
        //1163157884是一串数用来区分
        System.out.println(s2.hashCode());
        //1956725890
        //测试equals
        /**equals的方法默认实现是==比较比较的是两个对象的地址值
         * 进行对比，equals对比的是地址值false
         * 如果不想比较地址值，想比较类型+所有属性值
         * 需要重写此方法
         * 添加equals重写方法后 对比正确*/
        System.out.println(s.equals(s2));

    }
}

/**
 * 创建一个学生类
 */
class Student {
    int year;
    String name;

    public Student() {
    }

    public Student(int year, String name) {
        this.year = year;
        this.name = name;
    }

    /**
     * 重写Object中的toString()
     * 打印Student{year=20, name='yaya'}
     * 打印的对象的属性与属性值
     */
    @Override
    public String toString() {
        return "Student{" +
                "year=" + year +
                ", name='" + name + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {//判断地址符号
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Student student = (Student) o;
        return year == student.year &&
                Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(year, name);
    }
}